#include "command.h"

int commandReturn(int socketFd,char *fileName){

    // 接收服务端对命令路径的判断，以及执行结果
    // 返回TRUE正确且完成，PATHERROR 路径错误，GET下载命令 PUT 上传命令
    commandType ret;
    int r=recv(socketFd,&ret,sizeof(ret),MSG_WAITALL);
    if(r==0){
        printf("服务端关闭\n");
        return 1;
    }
    if(ret==PUTS){
        // 客户端上传文件，客户端发送
        sendFileToServer(socketFd,fileName);
    }
    else if(ret==GETS){
        printf("下载文件\n");
        // 客户端下载文件，客户端接收
        recvFileFromServer(socketFd);     
    }
    else if(ret==ERROR){
        // 路径错误，重新输入
        printf("路径错误，请重新输入命令\n");
    }
    else if(ret==PWD){
        // 接收路径长度
        int len;
        char path[64]={0};
        recv(socketFd,&len,sizeof(int),MSG_WAITALL);
        if(len!=-1){
            recv(socketFd,path,len,MSG_WAITALL);
        }
        printf("当前路径为%s\n",path);
    }
    else if(ret==LS){
        // 接收文件数量
        int n;
        int len;
        char name[32];
        recv(socketFd,&n,sizeof(int),MSG_WAITALL);
        printf("目录中共有 %d 个文件（非隐藏）:\n", n);
        for(int i=0;i<n;++i){
            memset(name,0,sizeof(name));
            recv(socketFd,&len,sizeof(int),MSG_WAITALL);
            recv(socketFd,name,len,MSG_WAITALL);
            printf("%s  ", name);
        }
        printf("\n");
    }
    else if(ret==TREE){
    }
    else if(ret==CD){
    }
    else if(ret==MKDIR){
        printf("创建成功\n");
    }
    else if(ret==RMDIR){
        printf("删除成功\n");
    }
    else if(ret==REMOVE){
        printf("删除成功\n");
    }
    return 0;
}

int commandRecognition(char *buf,train_t *train){
    char *savePtr=NULL;
    char *cmdtype=NULL;
    char *cmdpath=NULL;
    cmdtype=strtok_r(buf," ",&savePtr);
    cmdpath=strtok_r(NULL," ",&savePtr);
    if(strcmp(cmdtype,"cd")==0){
        train->command=CD;
    }
    else if(strcmp(cmdtype,"pwd")==0){
        train->command=PWD;
    }
    else if(strcmp(cmdtype,"ls")==0){
        train->command=LS;
    }
    else if(strcmp(cmdtype,"puts")==0){
        train->command=PUTS;
    }
    else if(strcmp(cmdtype,"gets")==0){
        train->command=GETS;
    }
    else if(strcmp(cmdtype,"rm")==0){
        train->command=REMOVE;
    }
    else if(strcmp(cmdtype,"rmdir")==0){
        train->command=RMDIR;
    }
    else if(strcmp(cmdtype,"mkdir")==0){
        train->command=MKDIR;
    }
    else if(strcmp(cmdtype,"tree")==0){
        train->command=TREE;
    }
    else{
        printf("命令无效,请重新输入\n");
        return -1;
    }
    if(cmdpath){
        train->argvSize=strlen(cmdpath);
        memcpy(train->argv,cmdpath,strlen(cmdpath));
    }
    else{
        train->argvSize=0;
    }
    return 0;
}
